﻿using System;
using System.Collections;
using System.Linq;
using Microsoft.Office.Server.Diagnostics;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Administration;
using Microsoft.SharePoint.Linq;
using OfficeLaunch.SharePoint.TwitterMap.Data;
using OfficeLaunch.SharePoint.TwitterMap.Twitter;

namespace OfficeLaunch.SharePoint.TwitterMap.TimerJobs
{
    public class GetTweets : SPJobDefinition
    {

        private const string HashTag = "#ANZOfficeLaunch";

        public GetTweets() :base()
        { }

        public GetTweets(string JobName, SPService JobService, SPServer JobServer, SPJobLockType TargetType) : base (JobName, JobService, JobServer, TargetType) 
        { }

        public GetTweets(string JobName, SPWebApplication WebApplication)
            : base(JobName, WebApplication, null, SPJobLockType.ContentDatabase)
        {
            Title = "Get Tweets";
        }

        public override void Execute(Guid TargetInstanceId)
        {
            var webApplication = Parent as SPWebApplication;
            if (webApplication == null) return;
            
            var contentDb = webApplication.ContentDatabases[TargetInstanceId];

            try
            {
                foreach (SPSite site in contentDb.Sites)
                {
                    try
                    {
                        // Checking to see if the list exists rather than the feature being turned on
                        // due to issue with SP2010 returning false results in pre RTM builds that
                        // were tested
                        if (site.RootWeb.Lists.Cast<SPList>().Where(List => List.Title == "Office Launch Tweets").Count() > 0)
                        {
                            using (var siteContext = new LinqDataContext(site.Url))
                            {
                                var tweets = TweetLoader.GetTweets(HashTag);

                                foreach (var tweet in from tweetObj in tweets
                                                      let tweet = tweetObj
                                                      where siteContext.OfficeLaunchTweets.Where(TweetItem => TweetItem.TweetID == tweet.ID).Count() < 1
                                                      select tweetObj)
                                {
                                    siteContext.OfficeLaunchTweets.InsertOnSubmit(new Tweet
                                    {
                                        Title = tweet.Text,
                                        TweetID = tweet.ID,
                                        TweetAuthor = tweet.Author,
                                        TweetTime = tweet.Time,
                                        TweetAuthorImage = tweet.AuthorImageUrl
                                    });
                                }
                                siteContext.SubmitChanges(ConflictMode.ContinueOnConflict);
                            }    
                        }
                    }
                    finally
                    {
                        site.Dispose();
                    }
                }
                using (var site = contentDb.Sites[0])
                {
                    // Commeted out the feature check as this appears to be an issue in SP2010
                    //if (site.Features.Where(Feature => Feature.DefinitionId == new Guid("bbd98944-241f-4beb-bc67-62b28945382e")).Count() > 0)
                    //{
                    
                    //}
                }
            }
            catch (Exception ex)
            {
                PortalLog.LogString("Error in GetTweet timer job: {0} - Stack Trace: {1}", ex.Message, ex.StackTrace);
            }
        }
    }
}
